package com.telnetnz.ticketdesk.bean;

import java.util.List;

import org.codehaus.jackson.map.annotate.JsonView;
import org.springframework.beans.BeanUtils;

import com.rockbb.common.simpleframe.config.SimpleConfig;
import com.rockbb.common.utilities.text.JacksonViews;
import com.rockbb.common.utilities.text.StringUtils;
import com.telnetnz.ticketdesk.bean.misc.OperationLogObject;
import com.telnetnz.ticketdesk.dao.entity.AttachmentEntity;
import com.telnetnz.ticketdesk.service.OperationLogService;
import com.telnetnz.ticketdesk.service.ProjectToUserService;
import com.telnetnz.ticketdesk.service.TicketCommentService;
import com.telnetnz.ticketdesk.service.TicketService;
import com.telnetnz.ticketdesk.service.UserService;

public class Attachment extends AttachmentEntity implements OperationLogObject 
{
	private static final long serialVersionUID = -8772924653606108047L;

	@JsonView(JacksonViews.Internal.class)
	public String getFormattedSize()
	{
		return StringUtils.formatFileSize(getSize());
	}

	@JsonView(JacksonViews.Internal.class)
	public String getFullPath()
	{
		return SimpleConfig.getConfig("file_physical_path") + SimpleConfig.getConfig("file_for_static") + getPath();
	}

	/**
	 * @return extension with '.' dot
	 */
	@JsonView(JacksonViews.Internal.class)
	public String getExtension()
	{
		return getPath().substring(getPath().lastIndexOf('.'));
	}

	public User getCreator() {
		return UserService.getUser(getCreatorId());
	}

	public TicketComment getComment() {
		return TicketCommentService.getTicketComment(getCommentId());
	}

	public Ticket getTicket() {
		return TicketService.getTicket(getTicketId());
	}

	public boolean isViewable(long userId)
	{ 
		Ticket ticket = getTicket();
		if (ticket == null) ticket = getComment().getTicket();
		if (ticket == null)
			return false;
		else
		{
			return ticket.isViewable(userId);
		}
	}

	public List<OperationLog> getOperationLogs()
	{
		return OperationLogService.getLogsByPageAndCondition(
				0, 
				10, 
				OperationLogService.ORDERBY_TIME, 
				0, 
				0L, 		// userId
				OperationLogService.OBJECT_TYPE_ATTACHMENT, // objectType
				getId(), 
				null, 
				null, 
				null);
	}

	public static Attachment adapt(AttachmentEntity entity) {
		if (entity == null)
			return null;
		Attachment bean = new Attachment();
		BeanUtils.copyProperties(entity, bean);
		return bean;
	}

	public AttachmentEntity toEntity() {
		return this;
	}

	public String getObjectName() {
		return getName();
	}

	public String getObjectSummary() {
		return getPath();
	}

}
